﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace System.Device.Location
{


    [DataContract]
    public class Address
    {
        [DataMember(Name = "city")]
        public String City { get; set; }

        [DataMember(Name = "district")]
        public String District { get; set; }

        [DataMember(Name = "province")]
        public String Province { get; set; }

        [DataMember(Name = "street")]
        public String Street { get; set; }

        [DataMember(Name = "street_number")]
        public String Street_number { get; set; }

    }

    /// <summary>
    /// GPS坐标转换辅助类
    /// 参考链接：http://www.cnblogs.com/jay-dong/archive/2013/03/13/2957648.html
    /// </summary>
    public static class LocationConverter
    {
        private static string GetXMLValue(string elementName, string xml)
        {
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(string.Format("<{0}>(.+?)</{0}>", elementName));
            var groups = reg.Matches(xml);
            if (groups.Count > 0)
                return groups[0].Groups[1].Value;
            return null;
        }
        /// <summary>
        /// 根据经纬度信息获取地址信息
        /// </summary>
        /// <param name="wg"></param>
        /// <param name="callback"></param>
        /// <param name="coordtype">坐标的类型，目前支持的坐标类型包括：bd09ll（百度墨卡托坐标）、gcj02ll（国测局墨卡托坐标）、wgs84ll（ wgs84经纬度）</param>
        public static void GeoCoordinateToAddress(GeoCoordinate wg, Action<CivicAddress> callback, string coordtype = "wgs84ll")
        {
            G.Net.HttpGet get = new G.Net.HttpGet("http://api.map.baidu.com/geocoder/v2/");
            get.Params.Add("ak", "3abb3bb9c18ba3e6078ff35a990e75bb");
            get.Params.Add("location", string.Format("{0},{1}", wg.Latitude, wg.Longitude));
            get.Params.Add("output", "xml");
            get.Params.Add("coordtype", coordtype);
            get.Request((sta, str) =>
            {
                if (sta == Net.WebExceptionStatus.Success)
                {
                    //正则表达式分析
                    if (GetXMLValue("status", str) == "0")
                    {
                        CivicAddress c = new CivicAddress();
                        c.AddressLine1 = GetXMLValue("formatted_address", str);
                        c.AddressLine2 = GetXMLValue("business", str);
                        c.City = GetXMLValue("city", str);
                        c.StateProvince = GetXMLValue("province", str);
                        callback(c);
                    }
                    else
                        callback(null);
                }
            });
        }

        /// <summary>
        /// 地球坐标转百度坐标
        /// </summary>
        /// <param name="wg"></param>
        /// <returns></returns>
        public static GeoCoordinate WordToBaidu(GeoCoordinate wg)
        {
            var mg = Transform(wg);
            return MarsToBaidu(mg);
        }
        #region 中国坐标和百度坐标互转
        /// <summary>
        /// 中国坐标转换成百度坐标
        /// </summary>
        /// <param name="mg">中国坐标</param>
        /// <returns>百度坐标</returns>
        public static GeoCoordinate MarsToBaidu(GeoCoordinate mg)
        {
            double x = mg.Longitude, y = mg.Latitude;

            double z = Math.Sqrt(x * x + y * y) + 0.00002 * Math.Sin(y * x_pi);

            double theta = Math.Atan2(y, x) + 0.000003 * Math.Cos(x * x_pi);

            double bd_lon = z * Math.Cos(theta) + 0.0065;

            double bd_lat = z * Math.Sin(theta) + 0.006;

            return new GeoCoordinate(bd_lat, bd_lon);
        }
        const double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        /// <summary>
        /// 百度坐标转换成火星坐标
        /// </summary>
        /// <param name="bdg"></param>
        /// <returns></returns>
        public static GeoCoordinate BaiduToMars(GeoCoordinate bdg)
        {
            double x = bdg.Longitude - 0.0065, y = bdg.Latitude - 0.006;

            double z = Math.Sqrt(x * x + y * y) - 0.00002 * Math.Sin(y * x_pi);

            double theta = Math.Atan2(y, x) - 0.000003 * Math.Cos(x * x_pi);

            double gg_lon = z * Math.Cos(theta);

            double gg_lat = z * Math.Sin(theta);
            return new GeoCoordinate(gg_lat, gg_lon);
        }
        #endregion

        #region 地球坐标转中国坐标
        const double pi = 3.14159265358979324;
        const double a = 6378245.0;
        const double ee = 0.00669342162296594323;

        /// <summary>
        /// 地球坐标转换成火星坐标（中国坐标）
        /// </summary>
        /// <param name="wg">地球坐标</param>
        /// <returns>中国坐标</returns>
        public static GeoCoordinate Transform(GeoCoordinate wg)
        {
            double lat;
            double lng;
            Transform(wg.Latitude, wg.Longitude, out lat, out lng);
            return new GeoCoordinate(lat, lng);
        }

        /// <summary>
        /// 地球坐标转换成火星坐标（中国坐标）
        /// </summary>
        /// <param name="wgLat"></param>
        /// <param name="wgLon"></param>
        /// <param name="mgLat"></param>
        /// <param name="mgLon"></param>
        public static void Transform(double wgLat, double wgLon, out double mgLat, out double mgLon)
        {
            if (outOfChina(wgLat, wgLon))
            {
                mgLat = wgLat;
                mgLon = wgLon;
                return;
            }
            double dLat = transformLat(wgLon - 105.0, wgLat - 35.0);
            double dLon = transformLon(wgLon - 105.0, wgLat - 35.0);
            double radLat = wgLat / 180.0 * pi;
            double magic = Math.Sin(radLat);
            magic = 1 - ee * magic * magic;
            double sqrtMagic = Math.Sqrt(magic);
            dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
            dLon = (dLon * 180.0) / (a / sqrtMagic * Math.Cos(radLat) * pi);
            mgLat = wgLat + dLat;
            mgLon = wgLon + dLon;
        }

        static bool outOfChina(double lat, double lon)
        {
            if (lon < 72.004 || lon > 137.8347)
                return true;
            if (lat < 0.8293 || lat > 55.8271)
                return true;
            return false;
        }

        static double transformLat(double x, double y)
        {
            double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.Sqrt(Math.Abs(x));
            ret += (20.0 * Math.Sin(6.0 * x * pi) + 20.0 * Math.Sin(2.0 * x * pi)) * 2.0 / 3.0;
            ret += (20.0 * Math.Sin(y * pi) + 40.0 * Math.Sin(y / 3.0 * pi)) * 2.0 / 3.0;
            ret += (160.0 * Math.Sin(y / 12.0 * pi) + 320 * Math.Sin(y * pi / 30.0)) * 2.0 / 3.0;
            return ret;
        }

        static double transformLon(double x, double y)
        {
            double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.Sqrt(Math.Abs(x));
            ret += (20.0 * Math.Sin(6.0 * x * pi) + 20.0 * Math.Sin(2.0 * x * pi)) * 2.0 / 3.0;
            ret += (20.0 * Math.Sin(x * pi) + 40.0 * Math.Sin(x / 3.0 * pi)) * 2.0 / 3.0;
            ret += (150.0 * Math.Sin(x / 12.0 * pi) + 300.0 * Math.Sin(x / 30.0 * pi)) * 2.0 / 3.0;
            return ret;
        }

        #endregion
    }
}
